using AdminApiTemplate.Common.Exceptions;
using AdminApiTemplate.Common.Helpers;
using AdminApiTemplate.Common.Models;
using AdminApiTemplate.Services.AdminUser.Models;
using Dapper;
using System.Data;
using System.Text;

namespace AdminApiTemplate.Services.AdminUser
{
    public class AdminUserService
    {
        private readonly IDbConnection _dbConnection;

        public AdminUserService(
            IDbConnection dbConnection)
        {
            _dbConnection = dbConnection;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public async Task<AdminUserDto> GetUserByNameAsync(string userName)
        {
            var sql = "select Id,UserName,ChineseName,EnglishName,UserPass,PassSalt,IsDisabled,UserType,WorkWx from AdminUser where UserName=@userName";
            var items = await _dbConnection.QueryFirstOrDefaultAsync<AdminUserDto>(sql, new { userName });
            return items;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public async Task<AdminUserDto> GetUserByWorkWxAsync(string workWx)
        {
            var sql = "select Id,UserName,ChineseName,EnglishName,IsDisabled,WorkWx from AdminUser where WorkWx=@workWx";
            var items = await _dbConnection.QueryFirstOrDefaultAsync<AdminUserDto>(sql, new { workWx });
            return items;
        }

        public async Task<IEnumerable<UserMenuDto>> GetUserMenusAsync(long userId)
        {
            var sql = @"
SELECT
	Id,
	ParentId,
	DisplayText,
	Url,
	Icon
FROM
	Permission p
WHERE
	p.IsMenu = 1
AND p.Id IN (
	SELECT
		rp.PermissionId
	FROM
		RolePermission rp
	WHERE
		rp.RoleId IN (
			SELECT
				ur.RoleId
			FROM
				UserRole ur
			WHERE
				ur.UserId =@userId
		)
	UNION
		SELECT
			up.PermissionId
		FROM
			UserPermission up
		WHERE
			up.UserId =@userId
)";
            var items = await _dbConnection.QueryAsync<UserMenuDto>(sql, new { userId });
            return items;
        }

        /// <summary>
        /// 获取用户权限
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<IEnumerable<PermissionDto>> GetUserPermissionAsync(long userId)
        {
            var sql = @"
            SELECT
            	Id,
            	ParentId,
            	DisplayText,
            	Url,
            	Icon,
            	IsMenu,
            	PermissionCode
            FROM
            	Permission p
            WHERE
            	p.Id IN (
            		SELECT
            			up.PermissionId
            		FROM
            			UserPermission up
            		WHERE
            			up.UserId =@userId
            	)";
            var items = await _dbConnection.QueryAsync<PermissionDto>(sql, new { userId });

            return items;

        }

        /// <summary>
        /// 获取用户权限【所有，用户管理，部门管理，角色管理】
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<IEnumerable<PermissionDto>> GetUserPermissionAllAsync(long userId)
        {
            var sql = @"SELECT Id,ParentId,DisplayText,Url,Icon,IsMenu,PermissionCode
                        FROM Permission p
                        WHERE	p.Id IN (
                        SELECT rp.PermissionId FROM RolePermission rp
                        WHERE rp.RoleId IN (
                        SELECT ur.RoleId FROM UserRole ur
                        WHERE ur.UserId =@userId )
                        union 
                        SELECT up.PermissionId FROM UserPermission up
                        WHERE up.UserId =@userId) ";
            var items = await _dbConnection.QueryAsync<PermissionDto>(sql, new { userId });
            return items;
        }

        public async Task<IEnumerable<PermissionDto>> GetPermissionAsync(bool? isMenu, int? parentId)
        {
            var filter = new StringBuilder();
            if (isMenu.HasValue)
            {
                if (isMenu.GetValueOrDefault())
                {
                    filter.Append(" and IsMenu=1 ");
                }
                else
                {
                    filter.Append(" and (IsMenu=0 or IsMenu is null) ");
                }
            }
            if (parentId.HasValue)
            {
                filter.Append($" and ParentId={parentId.GetValueOrDefault()} ");
            }
            var sql = $@"
SELECT
	Id,
	ParentId,
	DisplayText,
	Url,
	Icon,
	IsMenu,
	PermissionCode
FROM
	Permission p where 1=1 {filter}";
            var items = await _dbConnection.QueryAsync<PermissionDto>(sql);
            return items;
        }

        /// <summary>
        /// 获取管理员下拉选项
        /// </summary>
        /// <param name="request"></param>
        /// <param name="AUID"></param>
        /// <returns></returns>
        public async Task<IEnumerable<SelectItem>> GetAdminUserSelectAsync(GetAdminUserSelectRequestModel request, long AUID)
        {
            var dp = new DynamicParameters();
            var filter = new StringBuilder();
            if (!request.ViewAllData.GetValueOrDefault())
            {
                //不能查看全部 就只能查看自己跟管理的下级的数据
                dp.Add("AUID", AUID);
                filter.AppendLine($@" and Id IN (select @AUID union select UnderAUID from underauidmanage where AUID=@AUID) ");
            }

            if (!string.IsNullOrEmpty(request.Name))
            {
                dp.Add("Name1", $"%{request.Name}%");
                filter.Append(" and (`UserName` like @Name1 or `ChineseName` like @Name1 `EnglishName` like @Name1)");
            }

            if (request.UserType.HasValue)
            {
                if (request.UserType.GetValueOrDefault() == AdminUserTypeEnum.BD)
                {
                    filter.Append($" and `UserType` in ({(int)AdminUserTypeEnum.BM},{(int)AdminUserTypeEnum.BD}) ");
                }
                else if (request.UserType.GetValueOrDefault() == AdminUserTypeEnum.Sales)
                {
                    filter.Append($" and `UserType` in ({(int)AdminUserTypeEnum.BD},{(int)AdminUserTypeEnum.Sales}) ");
                }
                else
                {
                    dp.Add("UserType", request.UserType);
                    filter.Append(" and `UserType` = @UserType");
                }
            }

            if (request.IsDisabled.HasValue)
            {
                dp.Add("IsDisabled", request.IsDisabled);
                filter.Append(" and `IsDisabled` = @IsDisabled");
            }

            if (request.CanAssign.HasValue)
            {
                dp.Add("CanAssign", request.CanAssign);
                filter.Append(" and `CanAssign` = @CanAssign");
            }

            var sql = $"SELECT Id,UserName `Name` from AdminUser where 1=1 {filter} order by Id";
            var items = await _dbConnection.QueryAsync<SelectItem>(sql, dp);
            foreach (var item in items)
            {
                item.Name = $"#{item.Id} {item.Name}";
            }
            return items;
        }

        /// <summary>
        /// 管理的下级
        /// </summary>
        /// <param name="AUID"></param>
        /// <returns></returns>
        public async Task<IEnumerable<long>> GetUnderAUIDManagesListAsync(long AUID)
        {
            return await _dbConnection.QueryAsync<long>(@"select UnderAUID from underauidmanage where AUID=@AUID;", new { AUID });
        }

        /// <summary>
        /// 绑定用户企业微信
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="AUID"></param>
        /// <returns></returns>
        public async Task<string> BindUserWorkWxAsync(string userId, long AUID)
        {
            var sql = "update adminuser set WorkWx=@userId where Id=@AUID;";
            await _dbConnection.ExecuteAsync(sql, new { AUID, userId });

            sql = "insert into OperationLog(CreateTime,AUID,OperationType,P1,P2) select NOW(),@AUID,@OperationType,@AUID,@userId;";
            await _dbConnection.ExecuteAsync(sql, new { AUID, userId, OperationType = "BindWorkWx" });
            return "操作成功";
        }
        /// <summary>
        /// 查看账号邮箱密码
        /// </summary>
        /// <param name="Id">主键ID</param>
        /// <returns></returns>
        public string GetAdminUserEmailPassword(long Id)
        {
            return _dbConnection.ExecuteScalar<string>(@"select EmailPassword from adminuser WHERE Id=@Id;", new { Id });
        }
        /// <summary>
        /// 判断账号登录名是否存在
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public bool GetAdminUserUserName(string UserName)
        {
            return _dbConnection.ExecuteScalar<int>(@"select COUNT(1) from adminuser where UserName=@UserName;", new { UserName }) > 0;
        }
        /// <summary>
        /// 批量添加账号
        /// </summary>
        /// <param name="addAdminUserList"></param>
        /// <returns></returns>
        public string BatchAddAdminUser(List<BatchAddAdminUserExcelRequestModel> addAdminUserList)
        {
            var sb = new StringBuilder();
            var sb_error = new StringBuilder();
            var dp = new DynamicParameters();
            //判断excel表里面是否有相同的username
            var result = addAdminUserList.GroupBy(it => it.UserName).Select(it => new { Count = it.Count(), Name = it.Key });
            if (result.Where(it => it.Count > 1).Any())
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, $"excel存在相同的账号:{string.Join(',', result.Where(it => it.Count > 1).Select(it => it.Name))}");
            }
            IEnumerable<string> exists_username_list = _dbConnection.Query<string>(@"select UserName from adminuser where UserName in @UserNames;", new { UserNames = addAdminUserList.Select(it => it.UserName) });
            if (exists_username_list.Any())
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, $"数据库已存在相同的登录名:{string.Join(',', exists_username_list.Select(it => it))}");
            }
            for (int i = 0; i < addAdminUserList.Count; i++)
            {
                if (string.IsNullOrEmpty(addAdminUserList[i].UserName))
                {
                    sb_error.AppendLine($"第{i + 2}列的登录名必填;");
                }
                if (string.IsNullOrEmpty(addAdminUserList[i].UserType.ToString()))
                {
                    sb_error.AppendLine($"第{i + 2}列的用户类型必填;");
                }
                if (!int.TryParse(addAdminUserList[i].UserType.ToString(), out int usertype))
                {
                    sb_error.AppendLine($"第{i + 2}列的用户类型必须是数字;");
                }
                else
                {
                    sb.AppendLine($@"insert into adminuser(UserName,UserPass,PassSalt,IsDisabled,CreateTime,UserType,ChineseName,EnglishName,Email,EmailPassword)
                                 VALUES(@UserName_{i},'362b6cff87af94406f32cd02ea46068a87c37e13','arwsi7d7',0,now(),@UserType_{i},@ChineseName_{i},@EnglishName_{i},@Email_{i},@EmailPassword_{i});");
                    dp.Add($"@UserName_{i}", addAdminUserList[i].UserName);
                    dp.Add($"@UserType_{i}", addAdminUserList[i].UserType);
                    dp.Add($"@ChineseName_{i}", addAdminUserList[i].ChineseName);
                    dp.Add($"@EnglishName_{i}", addAdminUserList[i].EnglishName);
                    dp.Add($"@Email_{i}", addAdminUserList[i].Email);
                    dp.Add($"@EmailPassword_{i}", addAdminUserList[i].EmailPassword);
                }
            }
            if (sb_error.Length > 0)
                throw new WithCodeException(-3, sb_error.ToString());
            if (sb.Length > 0)
            {
                //插入成功之后需要插入到userrole表中
                bool flga = _dbConnection.Execute(sb.ToString(), dp) > 0;
                if (flga)
                {
                    TaskHelper.RunUseThread(() =>
                    {
                        InsertUserRole();
                    });
                }
                return flga ? "添加成功" : throw new WithCodeException(-4, "添加失败,请检查数据");
            }
            throw new WithCodeException(-5, "添加失败,请检查数据");
        }

        /// <summary>
        /// 添加用户角色
        /// </summary>
        public void InsertUserRole()
        {
            IEnumerable<AdminUserDto> insert_adminuser_dto = _dbConnection.Query<AdminUserDto>(@"select b.Id,b.UserType from adminuser b where Id not in (select a.UserId from userrole a where a.UserId=b.Id)  and b.IsDisabled=0 ;");
            if (insert_adminuser_dto.Any())
            {
                for (int i = 0; i < insert_adminuser_dto.Count(); i++)
                {
                    var dto = insert_adminuser_dto.ToList()[i];
                    _dbConnection.Execute(@"insert into userrole(UserId,RoleId,CreateTime)
                                                   values(@UserId,@RoleId,now());",
                                                   new
                                                   {
                                                       UserId = dto.Id,
                                                       RoleId = dto.UserType + 1
                                                   });
                }
            }
        }
        /// <summary>
        /// 修改账号权限
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string UpdateAdminUserByUserType(EditUserRoleUserTypeRequestModel request)
        {
            var sql = "update adminuser set UserType=@UserType where Id=@UserId;\r\n";
            if (request.ChangeRole.GetValueOrDefault())
            {
                sql += "update userrole set RoleId=@RoleId where UserId=@UserId;\r\n";
            }

            var rows = _dbConnection.Execute(sql, new
            {
                request.UserType,
                request.UserId,
                RoleId = request.UserType + 1
            });

            if (rows <= 0)
            {
                throw new WithCodeException(-1, "修改失败");
            }

            return "修改成功";
        }
        /// <summary>
        /// 修改上下级管理
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string UpdateUnderAuidManage(UpdateUnderAuidManageRequestModel request)
        {
            if (request.BM <= 0 || request.BD.Count == 0)
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "选择正确的分配数据");
            }
            string delete_sql = @"delete from underauidmanage where UnderAUID in @UnderAUID";
            string update_sql = @"update adminuser set ParentId=@AUID where Id in @UnderAUID";
            StringBuilder sb = new StringBuilder();
            DynamicParameters dp = new DynamicParameters();
            dp.Add("@AUID", request.BM);
            for (int i = 0; i < request.BD.Count; i++)
            {
                sb.AppendLine($@"insert into underauidmanage(AUID,UnderAUID)
                                                 values(@AUID,@UnderAUID_{i});");
                dp.Add($"@UnderAUID_{i}", request.BD[i]);
            }
            if (sb.Length == 0)
                return "修改失败";
            _dbConnection.Execute(delete_sql, new { UnderAUID = request.BD.ToArray() });
            _dbConnection.Execute(sb.ToString(), dp);
            _dbConnection.Execute(update_sql, new { UnderAUID = request.BD.ToArray(), AUID = request.BM });
            return "修改成功";
        }

        /// <summary>
        /// 修改销售等级
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string UpdateSalesLevel(UpdateSalesLevelRequestModel request)
        {
            string sql = @"update adminuser set `Level`=@Level where Id=@Id;";
            return _dbConnection.Execute(sql, new { request.Level, request.Id }) > 0 ? "修改成功" : "修改失败";
        }
        /// <summary>
        /// 修改BD分组
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string UpdateBDTeamId(UpdateSalesLevelRequestModel request)
        {
            string sql = @"update adminuser set TeamId=@TeamId where Id=@Id;";
            return _dbConnection.Execute(sql, new { TeamId = request.Level, request.Id }) > 0 ? "修改成功" : "修改失败";
        }

        /// <summary>
        /// 获取bd分组信息
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<SelectItem>> GetBDTeamListAsync()
        {
            var sql = "select Id,`Name` from adminuserteam where IsDisabled=0;";
            var items = await _dbConnection.QueryAsync<SelectItem>(sql);
            return items;
        }
        /// <summary>
        /// 获取javaid值
        /// </summary>
        /// <returns></returns>
        public async Task<int> GetJavaIdAsync(int id)
        {
            int JavaId = await _dbConnection.ExecuteScalarAsync<int>(@"select JavaId from adminuser where Id=@Id;", new { Id = id });
            return JavaId;
        }

        /// <summary>
        /// 获取用户权限树
        /// </summary>
        /// <param name="request"></param>
        /// <param name="AUID"></param>
        /// <returns></returns>
        public async Task<GetUserPermissionTreeResponseModel> GetUserPermissionTreeAsync(GetUserPermissionTreeRequestModel request, long AUID)
        {
            var rsp = new GetUserPermissionTreeResponseModel
            {
                CheckedPermissions = new List<string>(),
                AllPermissions = new List<GetPermissionTreeResponseModel>(),
            };
            var permissions = await GetUserPermissionAsync(request.AUID.GetValueOrDefault());
            if (permissions.Any())
            {
                rsp.CheckedPermissions = permissions.Select(o => o.Id.GetValueOrDefault().ToString()).ToList();
            }

            var tree = await GetPermissionTreeAsync(new GetPermissionTreeRequestModel(), AUID);
            if (tree.Any())
            {
                rsp.AllPermissions = tree;
            }

            return rsp;
        }

        /// <summary>
        /// 获取权限树
        /// </summary>
        /// <param name="request"></param>
        /// <param name="AUID"></param>
        /// <returns></returns>
        public async Task<List<GetPermissionTreeResponseModel>> GetPermissionTreeAsync(GetPermissionTreeRequestModel request, long AUID)
        {
            var tree = new List<GetPermissionTreeResponseModel>();
            var permissions = await GetPermissionAsync(request.IsMenu, request.ParentId);
            if (!permissions.Any())
            {
                return tree;
            }

            var topMenus = permissions.Where(w => w.ParentId.GetValueOrDefault() == 0);
            foreach (var menu in topMenus)
            {
                var node = new GetPermissionTreeResponseModel
                {
                    children = new List<GetPermissionTreeResponseModel>(),
                    id = menu.Id,
                    parentid = menu.ParentId,
                    isMenu = menu.IsMenu,
                    url = menu.Url,
                    code = menu.PermissionCode,
                    title = menu.DisplayText,
                    key = menu.Id.GetValueOrDefault()
                };
                tree.Add(node);
                BuildMenuTree(permissions, node);
            }

            return tree;
        }

        /// <summary>
        /// 构建菜单树
        /// </summary>
        /// <param name="menus"></param>
        /// <param name="node"></param>
        private void BuildMenuTree(IEnumerable<UserMenuDto> menus, GetPermissionTreeResponseModel node)
        {
            var children = menus.Where(w => w.ParentId.GetValueOrDefault().ToString() == node.key.GetValueOrDefault().ToString());
            foreach (var child in children)
            {
                var childNode = new GetPermissionTreeResponseModel
                {
                    children = new List<GetPermissionTreeResponseModel>(),
                    id = child.Id,
                    parentid = child.ParentId,
                    isMenu = child.IsMenu,
                    url = child.Url,
                    code = child.PermissionCode,
                    title = child.DisplayText,
                    key = child.Id.GetValueOrDefault()
                };
                node.children.Add(childNode);
                BuildMenuTree(menus, childNode);
            }
        }

        /// <summary>
        /// 初始化企业微信用户
        /// </summary>
        /// <param name="userIds"></param>
        /// <returns></returns>
        public async Task<string> InitWorkWxUserAsync(params string[] userIds)
        {
            var sql = "select Id,WorkWx from adminuser where WorkWx in @userIds";
            var users = await _dbConnection.QueryAsync<AdminUserDto>(sql, new { userIds });
            var users_add = userIds.Where(w => !users.Any(a => a.WorkWx == w)).ToList();

            sql = "select max(Id) from adminuser";
            var maxId = await _dbConnection.ExecuteScalarAsync<int>(sql);

            var sb = new StringBuilder();
            var dp = new DynamicParameters();
            for (var i = 0; i < users_add.Count; i++)
            {
                var item = users_add[i];
                sb.AppendLine($@"insert into adminuser(CreateTime,IsDisabled,UserName,ChineseName,EnglishName,WorkWx) values(NOW(),0,@WorkWx{i},@WorkWx{i},@WorkWx{i},@WorkWx{i});");
                dp.Add($"WorkWx{i}", item);
            }

            if (sb.Length > 0)
            {
                sql = sb.ToString();
                await _dbConnection.ExecuteAsync(sql, dp);
            }

            sql = $"insert into userrole(CreateTime,RoleId,UserId) select NOW(),1,Id from adminuser where Id>{maxId}";
            await _dbConnection.ExecuteAsync(sql);
            return "操作成功";
        }

        /// <summary>
        /// 初始化企业微信部门
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public async Task<string> InitWorkWxDepartmentAsync(params InitWorkWxDepartmentRequest[] departments)
        {
            var sql = "select Id from department where Id in @departmentIds";
            var departmentIds = departments.Select(o => o.Id);
            var departments_exist = await _dbConnection.QueryAsync<InitWorkWxDepartmentRequest>(sql, new { departmentIds });
            var departments_add = departments.Where(w => !departments_exist.Any(a => a.Id == w.Id)).ToList();

            var sb = new StringBuilder();
            var dp = new DynamicParameters();
            for (var i = 0; i < departments_add.Count; i++)
            {
                var item = departments_add[i];
                sb.AppendLine($@"insert into department(CreateTime,Id,ParentId,Sort) values(NOW(),@Id{i},@ParentId{i},@Sort{i});");
                dp.Add($"Id{i}", item.Id);
                dp.Add($"ParentId{i}", item.ParentId);
                dp.Add($"Sort{i}", item.Sort);
            }

            if (sb.Length > 0)
            {
                sql = sb.ToString();
                await _dbConnection.ExecuteAsync(sql, dp);
            }

            return "操作成功";
        }

        /// <summary>
        /// 获取所有用户信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<AdminUserDto>> GetAdminUserAllAsync()
        {
            var sql = "select Id,UserName,ChineseName,EnglishName,UserPass,PassSalt,IsDisabled,UserType,WorkWx from AdminUser ";
            var data = (await _dbConnection.QueryAsync<AdminUserDto>(sql)).ToList();
            return data;
        }

        /// <summary>
        /// 通过名称搜索信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task<List<UserInfoServiceModel>> GetAdminUserAsync(string name)
        {
            var sql = "select Id,ChineseName,EnglishName from adminuser where IsDisabled=0 and ChineseName LIKE " +
            $"'{name.Replace("'", "''").Replace("[", "[[]").Replace("%", "[%]").Replace("_", "[_]")}%' " +
            $"or EnglishName LIKE '{name.Replace("'", "''").Replace("[", "[[]").Replace("%", "[%]").Replace("_", "[_]")}%';";
            var items = await _dbConnection.QueryAsync<UserInfoServiceModel>(sql);
            return items.ToList();
        }

        /// <summary>
        /// 通过ID判断是否存在用户
        /// </summary>
        /// <param name="itemEvaluate"></param>
        /// <returns></returns>
        public bool GetAdminUserByIDAsync(int itemEvaluate)
        {
            var sql = "select id from adminuser where  IsDisabled=0 and id=@id";
            return _dbConnection.ExecuteScalar<int>(sql, new { id = itemEvaluate }) > 0 ? true : false;
        }

        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="request"></param>
        /// <param name="AUID"></param>
        /// <returns></returns>
        public async Task<string> AddPermissionAsync(AddPermissionRequestModel request, long AUID)
        {
            if (string.IsNullOrEmpty(request.PermissionCode))
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "权限编码必填", "PermissionCode必填");
            }

            var sql = "select Id from permission where PermissionCode =@PermissionCode";
            var id = await _dbConnection.ExecuteScalarAsync<int?>(sql, request);

            if (id.GetValueOrDefault() > 0)
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, $"已存在此权限编码：{request.PermissionCode}", $"已存在此PermissionCode：{request.PermissionCode}");
            }

            sql = @"
INSERT INTO permission (
	CreateTime,
	DisplayText,
	Icon,
	IsMenu,
	ParentId,
	PermissionCode,
	Url
)
VALUES
	(
		NOW(),
		@DisplayText,
		@Icon,
		@IsMenu,
		@ParentId,
		@PermissionCode,
		@Url
	)";
            await _dbConnection.ExecuteAsync(sql, request);
            return "添加成功";
        }

        /// <summary>
        /// 修改权限
        /// </summary>
        /// <param name="request"></param>
        /// <param name="AUID"></param>
        /// <returns></returns>
        public async Task<string> EditPermissionAsync(EditPermissionRequestModel request, long AUID)
        {
            if (request.Id.GetValueOrDefault() <= 0)
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "权限Id无效", "Id无效");
            }

            var sql = "select Id from permission where PermissionCode =@PermissionCode";
            var id = await _dbConnection.ExecuteScalarAsync<int?>(sql, request);

            if (id.HasValue && id != request.Id)
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, $"已存在此权限编码：{request.PermissionCode}", $"已存在此PermissionCode：{request.PermissionCode}");
            }

            sql = @"
UPDATE permission
SET DisplayText =@DisplayText,
 Icon =@Icon,
 IsMenu =@IsMenu,
 ParentId =@ParentId,
 PermissionCode =@PermissionCode,
 Url =@Url
WHERE
	Id =@Id";
            await _dbConnection.ExecuteAsync(sql, request);
            return "修改成功";
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        /// <param name="request"></param>
        /// <param name="AUID"></param>
        /// <returns></returns>
        public async Task<string> DelPermissionAsync(DelPermissionRequestModel request, long AUID)
        {
            if (request.PermissionIds == null || request.PermissionIds.Count == 0)
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "权限Id必填", "PermissionIds必填");
            }

            var sql = @"
DELETE FROM permission
WHERE
	Id in @Ids";
            await _dbConnection.ExecuteAsync(sql, new { Ids = request.PermissionIds.ToArray() });
            return "删除成功";
        }

        /// <summary>
        /// 分配权限
        /// </summary>
        /// <param name="request"></param>
        /// <param name="AUID"></param>
        /// <returns></returns>
        public async Task<string> AllocatePermissionAsync(AllocatePermissionRequestModel request, long AUID)
        {
            if (request.PermissionIds == null || request.PermissionIds.Count == 0)
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "权限Id必填", "PermissionIds必填");
            }

            if (request.AUIDs == null)
            {
                request.AUIDs = new List<int>();
            }

            if (request.RoleIds == null)
            {
                request.RoleIds = new List<int>();
            }

            if (request.DepartmentIds == null)
            {
                request.DepartmentIds = new List<int>();
            }

            if (request.AUIDs.Count == 0 && request.RoleIds.Count == 0 && request.DepartmentIds.Count == 0)
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "AUID,角色Id,部门Id必须填一个", "AUIDs,RoleIds,DepartmentIds必须填一个");
            }

            var sb = new StringBuilder();
            if (request.AUIDs.Any())
            {
                sb.AppendLine($"delete from userpermission where UserId in ({string.Join(",", request.AUIDs)});");
            }

            if (request.RoleIds.Any())
            {
                sb.AppendLine($"delete from rolepermission where RoleId in ({string.Join(",", request.RoleIds)});");
            }

            if (request.DepartmentIds.Any())
            {
                sb.AppendLine($"delete from departmentpermission where TeamId in ({string.Join(",", request.DepartmentIds)});");
            }

            foreach (var item_Permission in request.PermissionIds)
            {
                foreach (var item_AUID in request.AUIDs)
                {
                    sb.AppendLine($"insert into userpermission(CreateTime,UserId,PermissionId) values(NOW(),{item_AUID},{item_Permission});");
                }

                foreach (var item_RoleId in request.RoleIds)
                {
                    sb.AppendLine($"insert into rolepermission(CreateTime,RoleId,PermissionId) values(NOW(),{item_RoleId},{item_Permission});");
                }

                foreach (var item_DepartmentId in request.DepartmentIds)
                {
                    sb.AppendLine($"insert into departmentpermission(CreateTime,TeamId,PermissionId) values(NOW(),{item_DepartmentId},{item_Permission});");
                }
            }

            var sql = sb.ToString();
            await _dbConnection.ExecuteAsync(sql);
            return "分配成功";
        }

        /// <summary>
        /// 分配角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="AUID"></param>
        /// <returns></returns>
        public async Task<string> AllocateRoleAsync(AllocateRoleRequestModel request, long AUID)
        {
            if (!request.UserId.HasValue)
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "用户Id必填", "UserId必填");
            }

            if (request.RoleIds == null || request.RoleIds.Count == 0)
            {
                throw new WithCodeException((int)ErrorCodeEnum.InvalidArguments, "角色Id必填", "RoleIds必填");
            }

            var sql = $"delete from userrole where UserId={request.UserId}";
            var sb = new StringBuilder();
            foreach (var roleId in request.RoleIds)
            {
                sb.AppendLine($"insert into userrole(CreateTime,UserId,RoleId) values(NOW(),{request.UserId},{roleId});");
            }

            sql = sb.ToString();
            await _dbConnection.ExecuteAsync(sql);
            return "分配成功";
        }

        /// <summary>
        /// 添加登录日志
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task AddLoginLogAsync(AddLoginLogRequest request)
        {
            var sql = "insert into login_log(CreateTime,LogType,WorkWx,UserName,UserPass,Success,Remark) values(NOW(),@LogType,@WorkWx,@UserName,@UserPass,@Success,@Remark);";
            await _dbConnection.ExecuteAsync(sql, request);
        }
    }
}
